package com.qingge.springboot.controller;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingge.springboot.entity.User;
import com.qingge.springboot.mapper.CartMapper;
import com.qingge.springboot.utils.TokenUtils;
import io.swagger.models.auth.In;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingge.springboot.common.Result;

import com.qingge.springboot.service.ICartService;
import com.qingge.springboot.entity.Cart;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 黎俊
 * @since 2022-06-10
 */
@RestController
@RequestMapping("/cart")
public class CartController {

    @Resource
    private ICartService cartService;
    @Resource
    private CartMapper cartMapper;

    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody Cart cart) {
     Integer userId =    TokenUtils.getCurrentUser().getId();
        //更新购物车里相同的商品数量
        Integer goodsId = cart.getGoodsId();
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
         queryWrapper.eq("user_id",userId);
         queryWrapper.eq("goods_id",goodsId);
        Cart db = cartService.getOne(queryWrapper);
        if (db!=null){
            db.setNum(db.getNum()+cart.getNum());
            cartService.updateById(db);
            return Result.success();
        }

        //更新或新增
        if(cart.getId() ==null){
              cart.setTime(DateUtil.now());
                cart.setUserId(userId);
        }
        cartService.saveOrUpdate(cart);
        return Result.success();
    }

    @PostMapping("/num/{id}/{num}")
    public  Result updatNum(@PathVariable Integer id, @PathVariable Integer num){
        cartMapper.updateNum(num,id);
        return  Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        cartService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        cartService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(cartService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(cartService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam(defaultValue = "") String name) {
        User currentUser = TokenUtils.getCurrentUser();
        Integer userId = currentUser.getId();
        String role = currentUser.getRole();
        return Result.success(cartMapper.page(new Page<>(pageNum, pageSize), userId,role,name));
    }

}

